<!--
 * @Author: zhuhaohua 250293786@qq.com
 * @Date: 2024-01-02 10:21:51
 * @LastEditors: zhayang 1063975710@qq.com
 * @LastEditTime: 2024-06-22 22:19:00
 * @FilePath: \heart-backed\src\views\banner\index.vue
 * @Description: 图片上传
-->
<template>
  <div class="avatar-uploader-box">
    <el-upload class="avatar-uploader" drag :name="'filePath'" :multiple="false" :headers="postheaders" :data="postData"
      action="#" :show-file-list="false" :on-success="handleAvatarSuccess" accept=".jpg,.jpeg,.png,.gif"
      :before-upload="beforeAvatarUpload" :http-request="handleUploadImg">
      <img v-if="imageUrl && imageUrl !== ''" :src="imageUrl" class="avatar" />
      <div v-else class="up-show">
        <i :class="upIcon"></i>
        <p class="up-text">{{ upText }}</p>
      </div>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { getStsApi } from '@/api/upload'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    // 地址是否完整
    integrityAddress: {
      type: String,
      default: '1'
    },
    upIcon: {
      type: String,
      default: 'el-icon-plus avatar-uploader-icon'
    },
    upText: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 图片上传
      process: '',
      imageUrl: '',
      postheaders: {
        'Auth-Token': getToken()
      },
      stsData: {},
      fileData: {},
      postData: {
        key: '',
        policy: '',
        OSSAccessKeyId: '',
        signature: '',
        'x-oss-security-token': '' // 使用STS签名时必传。
      }
    }
  },
  watch: {
    url: {
      handler(nv, oldName) {
        if (nv) {
          if (this.integrityAddress === '0') {
            if (nv.indexOf('http') !== -1) {
              this.imageUrl = nv
            } else {
              this.imageUrl = process.env.VUE_APP_FILE_API + nv
            }
          } else {
            this.imageUrl = nv
          }
        } else {
          this.imageUrl = ''
        }
      },
      immediate: true
    }
  },
  created() {
    this.setData()
  },
  methods: {
    generateUUID() {
      const timestamp = Date.now().toString(16)
      const random = Math.random().toString(16).slice(2)
      return `${timestamp}${random}`
    },
    setData() {
      getStsApi()
        .then((res) => {
          this.stsData = res.data
          // this.process = this.stsData.host
          // this.process = '/up-api/'
        })
        .catch(() => { })
    },
    // 截取上传文件后缀
    getSuffix(filename) {
      const pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) suffix = filename.substring(pos)
      return suffix
    },
    handleAvatarSuccess(res, file) {
      // console.log('handleAvatarSuccess', res)
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.$emit('getImg', this.imageUrl)
    },
    beforeAvatarUpload(file) {
      this.fileData = file
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleUploadImg(file) {
      const that = this
      const signature = this.stsData.mp.signature
      const ossAccessKeyId = this.stsData.body.AccessKeyId
      const policy = this.stsData.mp.policy
      const key =
        this.stsData.file_path +
        this.generateUUID() +
        '.' +
        this.getSuffix(file.file.name)
      const securityToken = this.stsData.body.SecurityToken
      const formData = new FormData()
      formData.append('name', file.file.name) // 文件名称
      formData.append('key', key) // 存储在oss的文件路径
      formData.append('OSSAccessKeyId', ossAccessKeyId) // //accessKeyId
      formData.append('policy', policy) // policy
      formData.append('Signature', signature) // 签名
      formData.append('x-oss-security-token', securityToken) // 使用STS签名时必传。
      formData.append('success_action_status', 200)
      formData.append('file', file.file, file.file.name) // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可

      return new Promise((resolve, reject) => {
        axios
          .post(that.stsData.host, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Auth-Token': getToken()
            }
          })
          .then((rep) => {
            // console.log('rep', rep)
            if (rep.status === 200) {
              that.imageUrl = that.stsData.host + '/' + key
            }
            resolve(rep)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-box {
  ::v-deep {
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #04d1b8;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 80px;
      line-height: 80px;
      text-align: center;
    }

    .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }

    .iconfont {
      font-size: 28px;
      color: #1c1f23;
      width: 120px;
      height: 120px;
      text-align: center;
    }

    .el-upload-dragger {
      width: 100%;
      height: 100%;
      border: 0;

      .up-show {
        margin-top: 10px;
      }

      .up-text {
        font-weight: 400;
        font-size: 10px;
        color: #6a6b6c;
        line-height: 12px;
      }
    }
  }
}
</style>
